package cn.momoshenchi.product.exception;

import cn.momoshenchi.common.exception.BizCodeEnum;
import cn.momoshenchi.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @version : 1.0
 * @author: momoshenchi
 * @date: 2021/4/28 - 20:00
 */
@Slf4j
@ControllerAdvice
public class GlobalHandler
{
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R handle(Exception e)
    {
        e.printStackTrace(); //打印日志信息 ,超级重要
        Map<String,Object>map=new HashMap<>();
        if (e instanceof BindException)
        {
            BindException bindException = (BindException) e;
            map.put("msg", bindException.getBindingResult().getFieldError().getDefaultMessage());
        }
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",map);
    }
}
